unit wbDbPassword;

interface

uses SysUtils, Classes, DCPsha256, DCPrijndael;

type
  THashBytes = array [0 .. 31] of byte;

  TwbDbPassword = class(TComponent)
    Sha256: TDCP_sha256;
    Rijndael: TDCP_rijndael;
    function BytesToStr(hb: THashBytes): AnsiString;
    function HashBytes(str: AnsiString; id: integer): THashBytes;
    function DecStr(str, pwd: AnsiString; id: integer): AnsiString;
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  end;

implementation

function TwbDbPassword.BytesToStr(hb: THashBytes): AnsiString;
var
  s: AnsiString;
  j: integer;
begin
  s := '';
  for j := 0 to Length(hb) - 1 do // convert it into a hex string
    s := s + IntToHex(hb[j], 2);
  result := s;
end;

function TwbDbPassword.HashBytes(str: AnsiString; id: integer): THashBytes;
var
  HashDigest: THashBytes;
  salt: array [0 .. 1] of byte;
begin
  salt[0] := hi(id);
  salt[1] := lo(id);
  Sha256.Init;
  Sha256.Update(salt, sizeOf(salt));
  Sha256.UpdateStr(str);
  Sha256.Final(HashDigest);
  result := HashDigest;
end;

constructor TwbDbPassword.Create(AOwner: TComponent);
begin
  Sha256 := TDCP_sha256.Create(Self);
  Rijndael := TDCP_rijndael.Create(Self);
end;

function TwbDbPassword.DecStr(str, pwd: AnsiString; id: integer): AnsiString;
var
  HashDigest: THashBytes;
  se: AnsiString;
begin
  HashDigest := HashBytes(pwd, id);
  Rijndael.Init(HashDigest, sizeOf(HashDigest) * 8, nil);
  se := Rijndael.DecryptString(str);
  Rijndael.Burn;
  result := se;
end;

destructor TwbDbPassword.Destroy;
begin
  Sha256.Free;
  Rijndael.Free;
  inherited;
end;

end.
